package com.avecsys.quotemanager.validators;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

import org.springframework.web.jsf.FacesContextUtils;

import com.avecsys.quotemanager.exception.DAOException;
import com.avecsys.quotemanager.pojos.SupplierMasterPojo;
import com.avecsys.quotemanager.service.supplier.SupplierMasterService;
import com.avecsys.quotemanager.utils.MessageBoardUtil;
import com.avecsys.quotemanager.utils.UIComponentUtils;
import com.icesoft.faces.component.ext.HtmlInputHidden;

public class ValidatorSupplierEmailRegisteredCheck extends BaseValidator {
	public FacesMessage validateFieldValue(FacesContext facesContext,
			UIComponent uIComponent, Object object) throws ValidatorException {
		String emailInputField = (String) object;
		SupplierMasterService supplierMasterService = (SupplierMasterService) FacesContextUtils
				.getWebApplicationContext(facesContext).getBean(
						"supplierMasterService");
		FacesMessage message = new FacesMessage();
		SupplierMasterPojo supplierMasterPojo = new SupplierMasterPojo();
		HtmlInputHidden uiCcomponentSupplierId = (HtmlInputHidden) uIComponent
				.getParent().findComponent("supplierID");
		if (!UIComponentUtils.isEmpty(uiCcomponentSupplierId)) {
			supplierMasterPojo.setSupplierId(new Long(uiCcomponentSupplierId
					.getSubmittedValue().toString()));
		}
		supplierMasterPojo.setEmail(emailInputField);
		try {
			if (!supplierMasterService
					.isSupplierEmailNotRegistered(supplierMasterPojo)) {
				message.setSummary(MessageBoardUtil
						.getValue(
								facesContext,
								"supplierMsgs",
								"SERVICE_ERROR_SUPPLIER_EMAIL_REGISTERED_ALREADY",
								null));
			}
		} catch (DAOException e) {
			e.printStackTrace();
		}
		return message;
	}
}
